﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Modules.Device.Entitys;
using Modules.Device.Repositories;
using PmSoft;
using PmSoft.Exceptions;

namespace Modules.Device
{
    [UseDI(ServiceLifetime.Scoped)]
    public class CardReaderDeviceService
    {
        private readonly CardReaderRepository sysDeviceRepository;
        private readonly ILogger logger;

        public CardReaderDeviceService(CardReaderRepository sysDeviceRepository, ILogger<CardReaderDeviceService> logger)
        {
            this.sysDeviceRepository = sysDeviceRepository;
            this.logger = logger;
        }

        public CardReader? GetSysDevice(int id)
        {
            return sysDeviceRepository.Get(id);
        }

        public CardReader? GetSysDeviceByDeviceCode(string deviceCode)
        {
            return sysDeviceRepository.GetSysDeviceByDeviceCode(deviceCode);
        }

        public IPagedList<CardReader> GetSysDevices(DeviceQuery query, int pageIndex, int pageSize)
        {
            return sysDeviceRepository.GetSysDevices(query, pageIndex, pageSize);
        }

        public void DeleteSysDevice(int id)
        {
            sysDeviceRepository.DeleteByEntityId(id);
        }

        public void DeleteSysDevices(IEnumerable<int> ids)
        {
            foreach (int id in ids)
                DeleteSysDevice(id);
        }

        public void CreateSysDevice(CardReader sysDevice)
        {
            if (sysDeviceRepository.Exists(sysDevice, null))
                throw new BusinessException($"编码:{sysDevice.DeviceCode}已存在");
            sysDeviceRepository.Insert(sysDevice);
        }

        public void UpdateSysDevice(CardReader sysDevice)
        {
            if (sysDeviceRepository.Exists(sysDevice, sysDevice.Id))
                throw new BusinessException($"编码:{sysDevice.DeviceCode}已存在");
            sysDeviceRepository.Update(sysDevice);
        }

        /// <summary>
        /// 获取当前信息安全下的所有读卡器
        /// </summary>
        /// <param name="corpCode"></param>
        /// <returns></returns>
        public IEnumerable<CardReader> GetCardReaderDeviceByCorpCode(string corpCode)
        {
            return sysDeviceRepository.GetCardReaderDeviceByCorpCode(corpCode);
        }
    }
}